// pages/homework/bonusPoints/bonusPoints.js
import https from '../../../utils/request4.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    examId: null,
    title: null,
    gradeid: null,
    courseid: null,
    classId: null,
    options: [],
    selectedValue: {},
    showDropdown: false,
    examCourseId: null,
    studentTestQuestions: [],
    testQuestioninformation: {},
    selectPageInfo: {},
    imgWidth: 0,      // 图片原始宽度
    imgHeight: 0,     // 图片原始高度
    scale: 1,         // 当前缩放比例
    x: 100,             // X轴偏移
    y: -1200,              // Y轴偏移
    interval: false,
    intervalArr: [],
    intervalIndex: 0,
    intervalArrNumber: [],
  },
  toggleDropdown() {
    this.setData({
      showDropdown: !this.data.showDropdown
    });
  },
  selectItem(e) {
    const value = e.currentTarget.dataset.value;
    this.setData({
      selectedValue: value,
      showDropdown: false
    });
    wx.setStorageSync('questionInfo', JSON.stringify(value))
    this.calculateTheScore()
    this.nextQuestion()
  },
  calculateTheScore() {
    if (this.data.selectedValue.fullMarks < 11) {
        // 不需要选择分数区间
        this.setData({
            interval: false,
            intervalIndex: 0,
        })
    } else {
        // 需要选择分数区间
        // this.interval = true
        this.setData({
            interval: true
        })
    }
    let arrData = this.generateArrays(this.data.selectedValue.fullMarks)
    console.log(arrData);
    // let arr = []
    // for(let i= 0;i < Number(frequency); i++) {
    //     if (i == 0) {
    //         console.log('||||||||||||||');
    //         arr.push(`${i*10}-${(i+1)*10}`)
    //     } else {
    //         arr.push(`${i*10+1}-${(i+1)*10}`)
    //     }
    // }
    this.setData({
        intervalArr: arrData[0],
        intervalArrNumber: arrData[1],
    })
    console.log(this.data.intervalArr,'ppppppppppppp');
  },
  changeMenu(e) {
    this.setData({
        intervalIndex: e.currentTarget.dataset.index
    })
  },
  async setScores(e) {
        let data = {
            paperId: this.data.testQuestioninformation.paperId,
            paperQuestionId: this.data.selectedValue.id,
            option: String(e.currentTarget.dataset.value)
        }
        let options={
            url:'/scanpaperexception/submitscore',
            method:'post',
            data,
            header:{"content-type":"application/json;charset=UTF-8"}
        }
        let res = await https(options)
        if(res&&res.data.code==200){
            this.getInfo()
            this.nextQuestion()
        } else {
            wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000 //持续的时间
            })
        }
  },
  generateArrays(n) {
    const intervalStrs = [];
    const intervalNumbers = [];
    let start = 0;
    
    while (start <= n) {
        // 计算区间结束点
        let end = (Math.floor(start / 10) + 1) * 10;
        if (end > n) end = n;
        
        // 防止无效区间
        if (start > end) break;
        
        // 添加区间字符串
        intervalStrs.push(`${start}-${end}`);
        
        // 生成当前区间的数字数组
        const numbers = [];
        for (let i = start; i <= end; i++) {
            numbers.push(i);
        }
        intervalNumbers.push(numbers);
        
        // 更新下一个区间的起始值
        start = end + 1;
    }
    
    return [intervalStrs, intervalNumbers];
  },
  // 图片加载完成回调
  onImageLoad(e) {
    const { width, height } = e.detail
    this.setData({
      imgWidth: width,
      imgHeight: height
    })
  },

  // 视图变化回调（拖动/缩放时触发）
  onChange(e) {
    const { x, y, scale } = e.detail
    this.setData({ x, y, })
  },
  changScale(e) {
    const { x, y, scale } = e.detail
    // this.setData({ x, y,scale })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
        // examId: options.examId,
        // title: options.title,
        // gradeid: options.gradeid,
        // courseid: options.courseid,
        // classId: options.classId
        examCourseId: options.examCourseId,
      })
    this.getInfo()
  },
  async getInfo() {
        // 获取答题卡异常题目下拉列表
        let options={
            url:'/scoreexception/questionlist?examCourseId='+this.data.examCourseId,
            method:'get',
            header:{"content-type":"application/x-www-form-urlencoded"}
        }
        let res = await https(options)
        if(res&&res.data.code==200){
            let options = []
            res.data.data.map(ress => {
                if (ress.total > 0) {
                    options.push(ress)
                }
            })
            if (options.length == 0) {
                // 没题了，返回列表页
                wx.showToast({
                    title: '阅完了',
                    icon: 'none',
                    duration: 2000 //持续的时间
                })
                wx.redirectTo({
                    url: '/pages/homework/homeworkSituation/homeworkSituation?flag=1'
                })
                return
            }
            this.setData({
                options: options
            })
            //对题型进行缓存，如果当前列表有，则回显，否则显示第一个
            let questionInfo = null
            if (wx.getStorageSync('questionInfo')) {
                questionInfo = JSON.parse(wx.getStorageSync('questionInfo'))
            }
            if (questionInfo) {
                let arr = options.filter(item => {
                    return questionInfo.id == item.id
                })
                if (arr.length > 0) {
                    this.setData({
                        selectedValue: arr[0]
                    })
                } else {
                    if (options.length > 0) {
                        this.setData({
                            selectedValue: options[0]
                        })
                    }
                }
                this.calculateTheScore()
                this.nextQuestion()
            } else {
                if (options.length > 0) {
                    this.setData({
                        selectedValue: options[0]
                    })
                    this.calculateTheScore()
                    this.nextQuestion()
                }
            }
        } else {
            wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000 //持续的时间
            })
        }
  },
  async nextQuestion() {
        let data = {
            examCourseId: this.data.examCourseId,
            questionId: this.data.selectedValue.id
        }
        let options={
            url:'/scoreexception/next',
            method:'get',
            data: data,
            header:{"content-type":"application/x-www-form-urlencoded"}
        }
        let res = await https(options)
        if(res&&res.data.code==200){
            this.setData({
                testQuestioninformation: res.data.data,
                intervalIndex: 0,
            })
            if (this.data.testQuestioninformation.paperImages.length > 0) {
                this.setData({
                    selectPageInfo: this.data.testQuestioninformation.paperImages[this.data.testQuestioninformation.page - 1]
                })
            }
        } else {
            wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000 //持续的时间
            })
        }
  },
  downloadAndCrop(item) {
    wx.getImageInfo({
        src: item,
        success: (imageRes) => {
          const width = imageRes.width;  // 原始宽度
          const height = imageRes.height; // 原始高度
          console.log('图片原始宽高:', width, height);
          this.setData({
              imgWidth: width,
              imgHeight: height
          })
        },
        fail: (err) => {
          console.error('获取图片信息失败', err);
        }
      });
    wx.downloadFile({
      url: item,
      success: (res) => {
        this.cropImage(res.tempFilePath);
      },
      fail: (err) => {
        console.error('下载失败', err);
      }
    });
  },
  selectPage(e) {
    let item = e.currentTarget.dataset.item
    this.setData({
        selectPageInfo: item
    })
  },
  // 缩放事件处理
  onScale(e) {
    const { scale } = e.detail;
    this.setData({ scale });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})
// 节流函数工具
function throttle(fn, delay) {
    let lastTime = 0;
    return function(...args) {
      const now = Date.now();
      if (now - lastTime > delay) {
        fn.apply(this, args);
        lastTime = now;
      }
    };
  }